package com.opdar.athena.utils;

import com.opdar.athena.base.Message;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by shiju on 2017/7/2.
 */
public class MessageUtil {

    private static Map<Integer, Class<? extends Message>> messageTypes = new HashMap<Integer, Class<? extends Message>>();

    public static  <T extends Message> T newMessageTypeInstance(int type, byte[] body) {
        try {
            Class<? extends Message> messageType = messageTypes.get(type);
            try {
                Constructor<?> constructor = messageType.getDeclaredConstructor(byte[].class);
                constructor.setAccessible(true);
                return (T) constructor.newInstance(body);
            } catch (NoSuchMethodException e) {
                return (T) JSONUtil.parseObject(body, messageType);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void addMessageType(Integer type, Class<? extends Message> clz){
        messageTypes.put(type,clz);
    }

}
